package com.xinyue.cross.server.server.handler;

import com.xinyue.game.message.GameServerMessageModel;
import com.xinyue.game.message.GameServerRequestHeader;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettyDecoderHandler extends ChannelInboundHandlerAdapter {
    private static Logger logger = LoggerFactory.getLogger(NettyDecoderHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            ByteBuf byteBuf = (ByteBuf) msg;
            int size = byteBuf.readInt();
            GameServerRequestHeader messageHeader = new GameServerRequestHeader();
            messageHeader.read(byteBuf);
            GameServerMessageModel<GameServerRequestHeader> gameServerMessageModel = new GameServerMessageModel<>();
            gameServerMessageModel.setBody(byteBuf);
            gameServerMessageModel.setHeader(messageHeader);
            logger.debug("服务端收到消息,size: {}, header-> {}", size, messageHeader);
            ctx.fireChannelRead(gameServerMessageModel);

        } catch (Throwable e) {
            logger.error("服务器解析消息失败", e);
        }
    }
}
